#!/bin/bash

set -e

CONTRIB_ANDROID="$(dirname "$(readlink -e "$0")")"
ROOT_FOLDER="$CONTRIB_ANDROID"/../..
PACKAGES="$ROOT_FOLDER"/packages/
LOCALE="$ROOT_FOLDER"/electrum/locale/

if [ ! -d "$LOCALE" ]; then
  echo "Run pull_locale first!"
  exit 1
fi

if [ ! -d "$PACKAGES" ]; then
  echo "Run make_packages first!"
  exit 1
fi

pushd ./contrib/android

make theming

if [[ -n "$1"  && "$1" == "release" ]] ; then
    echo -n Keystore Password:
    read -s password
    export P4A_RELEASE_KEYSTORE=~/.keystore
    export P4A_RELEASE_KEYSTORE_PASSWD=$password
    export P4A_RELEASE_KEYALIAS_PASSWD=$password
    export P4A_RELEASE_KEYALIAS=electrum
    # build two apks
    export APP_ANDROID_ARCH=armeabi-v7a
    make release
    export APP_ANDROID_ARCH=arm64-v8a
    make release
else
    export P4A_DEBUG_KEYSTORE="$CONTRIB_ANDROID"/android_debug.keystore
    export P4A_DEBUG_KEYSTORE_PASSWD=unsafepassword
    export P4A_DEBUG_KEYALIAS_PASSWD=unsafepassword
    export P4A_DEBUG_KEYALIAS=electrum
    # create keystore if needed
    if [ ! -f "$P4A_DEBUG_KEYSTORE" ]; then
        keytool -genkey -v -keystore "$CONTRIB_ANDROID"/android_debug.keystore \
            -alias "$P4A_DEBUG_KEYALIAS" -keyalg RSA -keysize 2048 -validity 10000 \
            -dname "CN=mqttserver.ibm.com, OU=ID, O=IBM, L=Hursley, S=Hants, C=GB" \
            -storepass "$P4A_DEBUG_KEYSTORE_PASSWD" \
            -keypass "$P4A_DEBUG_KEYALIAS_PASSWD"
    fi
    # build two apks (only one on Travis CI)
    export APP_ANDROID_ARCH=arm64-v8a
    make apk
    if [ ! $CI ]; then
        export APP_ANDROID_ARCH=armeabi-v7a
        make apk
    fi
fi

popd
